How To Do Best Practices In JavaScript With Example

admin_img Posted By Bajarangi soft , Posted On 12-10-2020

Avoid global variables, avoid new, avoid ==, avoid eval in java script so today we discuss how to do it

How To Do Best Practices In JavaScript With Example

Avoid Global Variables

Minimize the use of global variables.

This includes all data types, objects, and functions.

Global variables and functions can be overwritten by other scripts.

Use local variables instead, and learn how to use closures.


Always Declare Local Variables

All variables used in a function should be declared as local variables.

Local variables must be declared with the var keyword or the let keyword, otherwise they will become global variables.

Strict mode does not allow undeclared variables.


Declarations on Top

It is a good coding practice to put all declarations at the top of each script or function.

This will:

  • Give cleaner code

  • Provide a single place to look for local variables

  • Make it easier to avoid unwanted (implied) global variablesReduce the possibility of unwanted re-declarations

// Declare at the beginning
var firstName, lastName, price, discount, fullPrice;

// Use later
firstName = "John";
lastName = "Doe";

price = 19.90;
discount = 0.10;

fullPrice = price - discount;
This also goes for loop variables:

// Declare at the beginning
var i;

// Use later
for (i = 0; i < 5; i++) {


 

Initialize Variables

It is a good coding practice to initialize variables when you declare them.

This will:

  • Give cleaner code

  • Provide a single place to initialize variables

  • Avoid undefined values

// Declare and initiate at the beginning
var firstName = "",
lastName = "",
price = 0,
discount = 0,
fullPrice = 0,
myArray = [],
myObject = {};


Never Declare Number, String, or Boolean Objects

Always treat numbers, strings, or booleans as primitive values. Not as objects.

Declaring these types as objects, slows down execution speed, and produces nasty side effects:
 

Example(1)

<script>
    var x = "John";        // x is a string
    var y = new String("John");  // y is an object
    document.getElementById("demo").innerHTML = x===y;
  
</script>


Example(2)

<script>
    var x = new String("John");
    var y = new String("John");
    document.getElementById("demo").innerHTML = x==y;
</script>

Don't Use new Object()

  • Use {} instead of new Object()

  • Use "" instead of new String()

  • Use 0 instead of new Number()

  • Use false instead of new Boolean()

  • Use [] instead of new Array()

  • Use /()/ instead of new RegExp()

  • Use function (){} instead of new Function()

 

Example(3)

<script>
    var x1 = {};
    var x2 = "";
    var x3 = 0;
    var x4 = false;
    var x5 = [];
    var x6 = /()/;
    var x7 = function(){};

    document.getElementById("demo"3).innerHTML =
        "x1: " + typeof x1 + "<br>" +
        "x2: " + typeof x2 + "<br>" +
        "x3: " + typeof x3 + "<br>" +
        "x4: " + typeof x4 + "<br>" +
        "x5: " + typeof x5 + "<br>" +
        "x6: " + typeof x6 + "<br>" +
        "x7: " + typeof x7 + "<br>";
</script>


Beware of Automatic Type Conversions

Beware that numbers can accidentally be converted to strings or NaN (Not a Number).

JavaScript is loosely typed. A variable can contain different data types, and a variable can change its data type:
Example(4)

var x = "Hello";     // typeof x is a string
x = 5;               // changes typeof x to a number

 

When doing mathematical operations, JavaScript can convert numbers to strings:


Example(5)

var x = 5 + 7;       // x.valueOf() is 12,  typeof x is a number
var x = 5 + "7";     // x.valueOf() is 57,  typeof x is a string
var x = "5" + 7;     // x.valueOf() is 57,  typeof x is a string
var x = 5 - 7;       // x.valueOf() is -2,  typeof x is a number
var x = 5 - "7";     // x.valueOf() is -2,  typeof x is a number
var x = "5" - 7;     // x.valueOf() is -2,  typeof x is a number
var x = 5 - "x";     // x.valueOf() is NaN, typeof x is a number
​​​​​​
 

Use === Comparison

The == comparison operator always converts (to matching types) before comparison.

The === operator forces comparison of values and type:

Example(6)

0 == "";        // true
1 == "1";       // true
1 == true;      // true

0 === "";       // false
1 === "1";      // false
1 === true;     // false


 

Use Parameter Defaults

If a function is called with a missing argument, the value of the missing argument is set to undefined.

Undefined values can break your code. It is a good habit to assign default values to arguments.
Example(7)

function myFunction(x, y) {
if (y === undefined) {
y = 0;
}
}

 

Avoid Using eval()

The eval() function is used to run text as code. In almost all cases, it should not be necessary to use it.

Because it allows arbitrary code to be run, it also represents a security problem.

Complete Cod For Best Practices In JavaScript With Example
 

<!DOCTYPE html>
<html>
<head>
    <title>How To Do Best Practices In JavaScript With Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<style>
    body {
        background: black;
    }
</style>
<body>
<div class="container">
    <br>
    <div class="text-center">
        <h2 id="color" style="color: White">How To Do Best Practices In JavaScript</h2>
    </div>
    <br>
    <br>
    <div class="well">
        <h2 id="demo1"></h2>
        <h2 id="demo2"></h2>
        <h2 id="demo3"></h2>
        <h2 id="demo4"></h2>
    </div>
</div>
</body>
</html>
<script>
    var x = "John";        // x is a string
    var y = new String("John");  // y is an object
    document.getElementById("demo1").innerHTML = x===y;
    document.getElementById("demo2").innerHTML = x==y;

    var x1 = {};
    var x2 = "";
    var x3 = 0;
    var x4 = false;
    var x5 = [];
    var x6 = /()/;
    var x7 = function(){};

    document.getElementById("demo3").innerHTML =
        "x1: " + typeof x1 + "<br>" +
        "x2: " + typeof x2 + "<br>" +
        "x3: " + typeof x3 + "<br>" +
        "x4: " + typeof x4 + "<br>" +
        "x5: " + typeof x5 + "<br>" +
        "x6: " + typeof x6 + "<br>" +
        "x7: " + typeof x7 + "<br>";

    // End Your Switches with Defaults
    //     Always end your switch statements with a default. Even if you think there is no need for it.
    var day;
    switch (new Date().getDay()) {
        case 0:
            day = "Sunday";
            break;
        case 1:
            day = "Monday";
            break;
        case 2:
            day = "Tuesday";
            break;
        case 3:
            day = "Wednesday";
            break;
        case 4:
            day = "Thursday";
            break;
        case 5:
            day = "Friday";
            break;
        case  6:
            day = "Saturday";
            break;
        default:
            day = "unknown";
    }
    document.getElementById("demo4").innerHTML = "Today is " + day;
</script>

 

Related Post